package com.eroad.product.tools;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;

public class RingView extends View {
	private float density; // 屏幕密度
	private float totalValue; // 总数
	private float viewWidth; // 控件宽度
	private float viewHeight; // 控件高度
	private float pieCenterX, pieCenterY, pieRadius; // 圆心X轴坐标，圆心Y轴坐标，圆半径
	private Paint textPaint, piePaint, linePaint, criclePaint;// 文本画笔，扇形画笔，线画笔,内圆画笔
	private RectF pieOval; // 矩形边界框
	private DecimalFormat df = new DecimalFormat("0.00");
	private float moreLine;
	private OnPieItemClickListener listener; // 点击柱状图的回调
	private List<Float> list_startX;// 文字X轴开始坐标
	private List<Float> list_startY;// 文字Y轴开始坐标
	private List<Float> list_endX; // 文字X轴结束坐标
	private List<Float> list_endY; // 文字Y轴结束坐标
	private String TAG = "RingView";
	private int[] color; // 值数据源
	private String[] title; // 文本数据源
	private double[] value; // 百分比数据源
	private float textSize = 12; // 字体大小
	private float cricle; // 内圆半径
	// 按下时x,y相对于中心点的坐标
	private float coordinatex;
	private float coordinatey;
	// 按下时的x,y的值
	private float downy;
	private float downx;
	// 抬起时的x,y的值
	private float upx;
	private float upy;
	// 用于计算点击处的角度
	private float absy;
	private float absx;
	// 扇形的弧度
	private ArrayList<Float> arraydegrees;

	public interface OnPieItemClickListener {
		public void onClick(int position);
	}

	public void setOnPieItemClickListener(OnPieItemClickListener listener) {
		this.listener = listener;
	}

	public RingView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub

	}

	public RingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
		DisplayMetrics displayMetrics = new DisplayMetrics();
		display.getMetrics(displayMetrics);
		density = displayMetrics.density;
	}

	public RingView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 设置数据源
	 * 
	 * @param pieItems
	 */
	public void setData(int[] color, String[] title, double[] value) {
		// this.mPieItems = pieItems;
		this.color = color;
		this.title = title;
		this.value = value;
		totalValue = 0;
		for (double item : value) {
			totalValue += item;
		}
		postInvalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		viewWidth = getWidth();
		viewHeight = getHeight();
		Log.i("wjj", density + "     density()");
		this.init();
		arraydegrees = new ArrayList<Float>();
		list_startX = new ArrayList<Float>();
		list_startY = new ArrayList<Float>();
		list_endX = new ArrayList<Float>();
		list_endY = new ArrayList<Float>();
		if (value != null && value.length > 0) {
			float start = 0.0f;
			for (int i = 0; i < color.length; i++) {
				piePaint.setColor(color[i]);// 设置颜色
				float sweep = (float) (value[i] / totalValue * 360);// 计算度数
				arraydegrees.add(sweep);
				canvas.drawArc(pieOval, start, sweep, true, piePaint);// 画扇形
				start += sweep;
			}
			canvas.drawCircle(pieCenterX, pieCenterY, cricle, criclePaint);
			start = 0.0f;
			for (int i = 0; i < value.length; i++) {
				float sweep = (float) (value[i] / totalValue * 360);// 计算度数
				float radians = (float) ((start + sweep / 2) / 180 * Math.PI);// 扇形中间度数
				float lineStartX = pieCenterX + pieRadius * (float) (Math.cos(radians));
				float lineStartY = pieCenterY + pieRadius * (float) (Math.sin(radians));
				float lineStopX, lineStopY;
				lineStopX = pieCenterX + (pieRadius + 15 * density) * (float) (Math.cos(radians));
				lineStopY = pieCenterY + (pieRadius + 15 * density) * (float) (Math.sin(radians));
				if (list_endY.size() >= 1 && Math.abs(list_endY.get(i - 1) - lineStopY) < textSize) {
					if (lineStartY > pieCenterY) {
						lineStopY = list_endY.get(i - 1) + textSize;
					} else {
						lineStopY = list_endY.get(i - 1) - textSize;
					}
				}
				canvas.drawLine(lineStartX, lineStartY, lineStopX, lineStopY, linePaint);
				if (lineStartX > pieCenterX) {
					canvas.drawLine(lineStopX, lineStopY, lineStopX + moreLine, lineStopY, linePaint);
					lineStopX = lineStopX + moreLine;
				} else {
					canvas.drawLine(lineStopX, lineStopY, lineStopX - moreLine, lineStopY, linePaint);
					lineStopX = lineStopX - moreLine;
				}
				String itemPercentText = title[i];// 数据源百分比
				float itemPercentTextLen = textPaint.measureText(itemPercentText);// 数据源百分比长度
				float percentStartX = lineStopX;
				float percentStartY = lineStopY;
				if (lineStartX > pieCenterX) {
					if (percentStartX + itemPercentTextLen > viewWidth) {
						percentStartX = viewWidth - itemPercentTextLen;
					}
				} else {
					percentStartX -= itemPercentTextLen;
					if (percentStartX < 0) {
						percentStartX = 0;
					}
				}
				if (lineStartY > pieCenterY) {
					if (percentStartY > viewHeight) {
						percentStartY = viewHeight;
					}
				} else {
					if (percentStartY - textPaint.getTextSize() < 0) {
						percentStartY = textPaint.getTextSize();
					}
				}
				canvas.drawText(itemPercentText, percentStartX, percentStartY, textPaint);// 百分比(文字)
				list_startX.add(percentStartX);
				list_startY.add(percentStartY - textPaint.getTextSize() - 5 * density);
				list_endX.add(percentStartX + itemPercentTextLen);
				list_endY.add(percentStartY + 5 * density);
				start += sweep;
			}
		}
	}

	public void init() {
		float min = Math.min(viewWidth, viewHeight);
		pieCenterX = viewWidth / 2;
		pieCenterY = viewHeight / 2;
		pieRadius = min / 3;
		moreLine = 5 * density;
		// cricle = min / 6;
		cricle = 0;
		textSize = 12 * density;
		pieOval = new RectF(pieCenterX - pieRadius, pieCenterY - pieRadius, pieCenterX + pieRadius, pieCenterY + pieRadius);

		textPaint = new Paint();
		textPaint.setAntiAlias(true);
		textPaint.setStyle(Paint.Style.FILL);
		textPaint.setTextSize(textSize);
		textPaint.setColor(Color.parseColor("#336699"));// 颜色

		piePaint = new Paint();
		piePaint.setAntiAlias(true);
		piePaint.setStyle(Paint.Style.FILL);

		linePaint = new Paint();
		linePaint.setAntiAlias(true);
		linePaint.setStyle(Paint.Style.FILL);
		linePaint.setStrokeWidth(1);
		linePaint.setColor(Color.parseColor("#939393"));// 颜色

		criclePaint = new Paint();
		criclePaint.setAntiAlias(true);
		criclePaint.setStyle(Paint.Style.FILL);
		criclePaint.setColor(Color.parseColor("#ffffff"));
	}

	public float getmoreLine(float radius) {
		int a = (int) (radius % 360 / 90);
		switch (a) {
		case 0:
			return moreLine;
		case 1:
			return 0 - moreLine;
		case 2:
			return 0 - moreLine;
		case 3:
			return moreLine;
		}
		return moreLine;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.i("wjj", event.getX() + "  event.getX()");
			Log.i("wjj", event.getY() + "  event.getY()");
			// 按下时候的x，y
			downx = event.getX();
			downy = event.getY();
			// 计算按下的x,y与坐标中点的距离
			absx = Math.abs(downx - pieCenterX);
			absy = Math.abs(downy - pieCenterY);
			// 按下时x,y相对于中心点的坐标
			coordinatex = (downx - pieCenterX);
			coordinatey = (pieCenterY - downy);
			if (event.getY() >= 0 && event.getY() <= viewHeight && event.getX() >= 0 && event.getX() <= viewWidth) {
				if (list_startX != null && list_startY != null && list_endX != null && list_endY != null) {
					for (int i = 0; i < list_startX.size(); i++) {
						if (event.getX() >= list_startX.get(i) && event.getX() <= list_endX.get(i)
								&& event.getY() >= list_startY.get(i) && event.getY() <= list_endY.get(i)) {
							if (listener != null) {
								listener.onClick(i);
							}
							break;
						}
					}
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			// 抬起来时候的x,y
			upx = event.getX();
			upy = event.getY();
			boolean t = ((upx - downx) * (upx - downx) + (upy - downy) * (upy - downy)) < 25;
			float a = absx * absx + absy * absy;
			if (a <= pieRadius * pieRadius && a >= cricle * cricle && t) {
				double jiaodu = getangle(absx, absy, coordinatex, coordinatey);
				itemClicke(jiaodu);
			}
			break;
		}

		return true;
	}

	/**
	 * 
	 * @param 用于计算正切值的x
	 * @param 用于计算正切值的y
	 * @param downx
	 *            downy 用于判断按下时候 在第几块
	 * @return 得到按下时候的角度
	 */
	protected double getangle(float x, float y, float downx, float downy) {
		double angle = 0.0;
		if (downx > 0 && downy < 0) {
			double c = (double) y / (double) x;
			double d = Math.toDegrees(Math.atan(c));
			angle = d;
		} else if (downx <= 0 && downy <= 0) {
			double c = (double) x / (double) y;
			double d = Math.toDegrees(Math.atan(c));
			angle = d + 90;
		} else if (downx < 0 && downy >= 0) {
			double c = (double) y / (double) x;
			double d = Math.toDegrees(Math.atan(c));
			angle = 180 + d;
		} else {
			double c = (double) x / (double) y;
			double d = Math.toDegrees(Math.atan(c));
			angle = d + 270;
		}
		return angle;
	}

	// 添加监听事件
	protected void itemClicke(double jiaodu) {
		float jianji = (float) jiaodu;
		float b = 0;
		float c = arraydegrees.get(0);
		System.out.println(jianji);
		for (int i = 0; i < arraydegrees.size(); i++) {
			if (jianji > b && jianji < c) {
				if (listener != null) {
					listener.onClick(i);
				}
				return;
			}
			b = b + arraydegrees.get(i);
			c = b + arraydegrees.get(i + 1);
		}
	}

}
